import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;

public class SyncThread extends Thread {
    private Journal journal;
    private ArrayList<ServerDescriptor> slaves;

    public SyncThread(Journal journal, ArrayList<ServerDescriptor> slaveList){
        this.journal = journal;
        this.slaves = slaveList;
    }
    public void run() {
        try {

            while(true)
            {
                journal.flushToFile();
                Thread.sleep(10000);
                if(slaves.size() == 0)
                {
                    continue;
                }

                synchronized (slaves) {
                    sendJournalToSlaves(slaves, journal);
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            print("Some IO Exception occured when trying to send journal");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    private void print(String s) {
        System.out.println(s);
    }
    public void sendJournalToSlaves(ArrayList<ServerDescriptor> slaveList, Journal log) throws IOException, ClassNotFoundException {
        for (ServerDescriptor slave : slaveList) {
            Journal changes;
            Date lastupdated = slave.getlastSyncDate();
            changes = lastupdated == null ? log : log.getLastChanges(lastupdated);
            if(changes.getRecords().size() > 0) {
                Socket slaveSocket = new Socket(slave.address, slave.port);
                Serialization.writeObject(slaveSocket, changes );
                print(Serialization.readObject(slaveSocket).toString());
                slaveSocket.close();
            }
        }
    }
}